const app = getApp();
// pages/user/manager/goods/goods.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    categoryList: [],
    goodsList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init();
  },

  init(){
    var _this = this
    app.getCategory().then(data => {
      if(data.allCategory.length === 0){
        data.allCategory.push({categoryName: "", categorySort: 1})
      }
      _this.setData({
        categoryList: data.allCategory, 
      })
      var activeKey = _this.data.activeKey;
      if(activeKey != null){
        _this.switchSidebar(activeKey);
      }else{
        _this.switchSidebar(0);
      }
    });
  },

  switchSidebar(index){
    var _this = this
    var categoryList = _this.data.categoryList;
    var categoryName = categoryList[index].categoryName;
    var categoryId = categoryList[index].categoryId;
    var status = categoryList[index].status;
    _this.setData({ 
      activeKey: index, 
      categoryName: categoryName, 
      categoryId: categoryId , 
      status: status 
    });
    if(categoryId != null && categoryId != undefined){
      _this.queryGoodsByCategoryId(categoryId);
    }
  },

  queryGoodsByCategoryId(categoryId){
    var _this = this;
    app.request('/goods/getBy/' + categoryId, 'GET', {})
    .then(data => {
      if (data.code === 0) {
        var goodsList = data.goodsList;
        for(var i = 0; i < goodsList.length; i++){
          goodsList[i].goodsImg = app.getFileUrl(goodsList[i].goodsImg)
        }
        _this.setData({
          goodsList: goodsList
        })
      } else {
        wx.showToast({
          title: data.msg || '请求失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      console.error(err)
      wx.showToast({
        title: '服务繁忙',
        icon: 'none'
      });
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.init();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  /**
   * 编辑商品
   */
  editGoods(e){
    var categoryId = this.data.categoryId;
    var goodsId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/user/manager/goods/editGoods/editGoods?categoryId=' + categoryId + '&goodsId=' + goodsId,
    })
  },

  addGoods(){
    var categoryId = this.data.categoryId;
    wx.navigateTo({
      url: '/pages/user/manager/goods/editGoods/editGoods?categoryId=' + categoryId,
    })
  },

  onSidebarChange(event){
    var _this = this
    var index = event.detail; // 当前选中的索引
    _this.switchSidebar(index);
  }
})